package com.xbongbong.pay.platform.unionpay.config;

import com.xbongbong.pay.platform.unionpay.utils.UnionPayCertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 *
 * @author 魏荣杰
 * @date 2021/1/22 09:38
 * @since
 * @version
 */
@Configuration
@Conditional(UnionPayConfigCondition.class)
@EnableConfigurationProperties(UnionPayConfig.class)
public class UnionPayMetaConfiguration {
    private static final Logger LOG = LoggerFactory.getLogger(UnionPayMetaConfiguration.class);

    @Bean
    @ConditionalOnMissingBean
    public UnionPayMetaContainer unionPayMetaContainer(UnionPayConfig unionPayConfig) {
        UnionPayMetaContainer unionPayMetaContainer = new UnionPayMetaContainer();
        Map<String, UnionPayConfig.Config> config = unionPayConfig.getConfig();
        config.forEach((k, v) -> {
            try {
                KeyStore keyStore = UnionPayCertUtil.getKeyStore(v.getSignCertPath(), v.getSignCertPwd(), v.getSignCertType());
                String signCertId = UnionPayCertUtil.getSignCertId(keyStore);
                X509Certificate x509Certificate = UnionPayCertUtil.initCert(v.getEncryptCertPath());
                UnionPayMeta unionPayMeta = new UnionPayMeta();
//                UnionPayMeta unionPayMeta = UnionPayCertUtil.createUnionPayMeta(v.getSignCertPath(), v.getSignCertType(), v.getSignCertPwd());
                unionPayMeta.setSerialNumber(signCertId);
                unionPayMeta.setCertificate(x509Certificate);
                unionPayMeta.setKeyStore(keyStore);
                unionPayMeta.setId(k);
                unionPayMeta.setConfig(v);
                unionPayMetaContainer.addUnionPayMeta(unionPayMeta);
            } catch (Exception e) {
                LOG.error("com.xbongbong.pay.platform.unionpay.config.UnionPayMetaContainer.unionPayMetaContainer error", e);
            }
        });
        return unionPayMetaContainer;
    }
}
